﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace Pavilion.DesignerTool
{
    /// <summary>
    /// Interaction logic for LayerContainerView.xaml
    /// </summary>
    public partial class LayerContainerView : UserControl, INotifyPropertyChanged
    {
        public static readonly DependencyProperty CurrentFrameDataProperty = DependencyProperty.Register("CurrentFrameData", typeof(FrameData), typeof(LayerContainerView),
            new PropertyMetadata(new PropertyChangedCallback(CurrentFrameDataChanged)));

        public event PropertyChangedEventHandler PropertyChanged;

        private TextureData _currentLayer;
        public TextureData CurrentLayer { get { return _currentLayer; } set { _currentLayer = value; OnPropertyChanged("CurrentLayer"); } }
        public FrameData CurrentFrameData { get { return (FrameData)GetValue(CurrentFrameDataProperty); } set { SetValue(CurrentFrameDataProperty, value); } }

        private LayerContainerViewModel _viewModel;

        public LayerContainerView()
        {
            this.DataContext = _viewModel = new LayerContainerViewModel();
            InitializeComponent();
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void RemoveItem_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.RemoveLayer(CurrentLayer);

            if (_viewModel.LayerCollection.Count > 0)
                CurrentLayer = _viewModel.LayerCollection[0];
        }

        private void InsertItem_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.InsertNewLayer(_viewModel.LayerCollection.IndexOf(CurrentLayer));
        }

        static private void CurrentFrameDataChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            LayerContainerView view = (LayerContainerView)dependencyObject;

            view._viewModel.LoadFrame(view.CurrentFrameData);

            if (view.CurrentFrameData == null || view.CurrentFrameData.TextureDataCollection.Count == 0)
                view.CurrentLayer = null;
            else
                view.CurrentLayer = view.CurrentFrameData.TextureDataCollection[0];
        }

        private void AddLayer_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = (CurrentFrameData != null); }
        private void AddLayer_Executed(object sender, ExecutedRoutedEventArgs e) { _viewModel.AddLayer(); }
    }
}
